#!/bin/bash

################################################################################
# MinIO 集群配置更新脚本
# 功能: 在所有 MinIO 节点上更新域名配置
# 使用: ./update-minio-config.sh
################################################################################

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# MinIO 节点列表
NODES=("minio1" "minio2" "minio3" "minio4")

# 配置参数
SERVICE_FILE="/etc/systemd/system/minio.service"
OLD_SERVER_URL='Environment="MINIO_SERVER_URL=http://10.1.1.103:9100"'
NEW_SERVER_URL='Environment="MINIO_SERVER_URL=https://bigdata.data.jichuangmao.com"'
OLD_BROWSER_URL='Environment="MINIO_BROWSER_REDIRECT_URL=http://10.1.1.103:9190"'
NEW_BROWSER_URL='Environment="MINIO_BROWSER_REDIRECT_URL=https://bigdata-ui.data.jichuangmao.com"'

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}MinIO 集群配置更新脚本${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# 函数: 测试 SSH 连接
test_ssh_connection() {
    local node=$1
    if ssh -o ConnectTimeout=5 -o BatchMode=yes ${node} "echo 'connected'" &>/dev/null; then
        return 0
    else
        return 1
    fi
}

# 函数: 更新单个节点
update_node() {
    local node=$1
    local node_num=$2
    local total=$3
    
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}[${node_num}/${total}] 节点: ${node}${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    
    # 检查节点连接
    echo -ne "  检查连接... "
    if ! test_ssh_connection ${node}; then
        echo -e "${RED}❌ 失败${NC}"
        echo -e "${RED}  错误: 无法连接到节点 ${node}${NC}"
        echo -e "${YELLOW}  提示: 请检查 SSH 配置和网络连接${NC}"
        return 1
    fi
    echo -e "${GREEN}✓${NC}"
    
    # 检查服务文件是否存在
    echo -ne "  检查服务文件... "
    if ! ssh ${node} "test -f ${SERVICE_FILE}" 2>/dev/null; then
        echo -e "${RED}❌ 失败${NC}"
        echo -e "${RED}  错误: 服务文件不存在: ${SERVICE_FILE}${NC}"
        return 1
    fi
    echo -e "${GREEN}✓${NC}"
    
    # 备份原配置
    echo -ne "  备份配置文件... "
    if ssh ${node} "cp ${SERVICE_FILE} ${SERVICE_FILE}.backup.\$(date +%Y%m%d_%H%M%S)" 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
    else
        echo -e "${YELLOW}⚠ 备份失败，继续更新${NC}"
    fi
    
    # 更新配置
    echo -ne "  更新域名配置... "
    if ssh ${node} "sed -i 's|${OLD_SERVER_URL}|${NEW_SERVER_URL}|g' ${SERVICE_FILE}" 2>/dev/null && \
       ssh ${node} "sed -i 's|${OLD_BROWSER_URL}|${NEW_BROWSER_URL}|g' ${SERVICE_FILE}" 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
    else
        echo -e "${RED}❌ 失败${NC}"
        echo -e "${RED}  错误: sed 命令执行失败${NC}"
        return 1
    fi
    
    # 验证配置
    echo -ne "  验证配置... "
    if ssh ${node} "grep -q 'bigdata.data.jichuangmao.com' ${SERVICE_FILE}" 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
    else
        echo -e "${RED}❌ 失败${NC}"
        echo -e "${RED}  错误: 配置验证失败，域名未找到${NC}"
        return 1
    fi
    
    # 显示更新后的配置
    echo -e "  ${CYAN}新配置内容:${NC}"
    ssh ${node} "grep 'MINIO_SERVER_URL\|MINIO_BROWSER_REDIRECT_URL' ${SERVICE_FILE}" 2>/dev/null | sed 's/^/    /'
    
    echo -e "${GREEN}  ✅ 节点 ${node} 配置更新成功${NC}"
    return 0
}

# 主流程
echo -e "${BLUE}准备更新 ${#NODES[@]} 个节点...${NC}"
echo ""

# 首先测试所有节点的连接
echo -e "${YELLOW}测试节点连接...${NC}"
UNREACHABLE_NODES=()
for node in "${NODES[@]}"; do
    echo -ne "  ${node}... "
    if test_ssh_connection ${node}; then
        echo -e "${GREEN}✓${NC}"
    else
        echo -e "${RED}❌${NC}"
        UNREACHABLE_NODES+=("${node}")
    fi
done
echo ""

if [ ${#UNREACHABLE_NODES[@]} -gt 0 ]; then
    echo -e "${YELLOW}⚠️  以下节点无法连接: ${UNREACHABLE_NODES[*]}${NC}"
    echo -e "${YELLOW}将跳过这些节点，继续更新其他节点${NC}"
    echo ""
fi

# 更新所有节点
SUCCESS_COUNT=0
FAILED_NODES=()
SKIPPED_NODES=()

for i in "${!NODES[@]}"; do
    node="${NODES[$i]}"
    node_num=$((i + 1))
    total=${#NODES[@]}
    
    # 跳过无法连接的节点
    if [[ " ${UNREACHABLE_NODES[@]} " =~ " ${node} " ]]; then
        echo -e "${YELLOW}[${node_num}/${total}] 跳过节点: ${node} (无法连接)${NC}"
        SKIPPED_NODES+=("${node}")
        echo ""
        continue
    fi
    
    # 更新节点
    if update_node ${node} ${node_num} ${total}; then
        ((SUCCESS_COUNT++))
    else
        FAILED_NODES+=("${node}")
    fi
    echo ""
done

# 汇总结果
echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}更新结果汇总${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

echo -e "总节点数: ${CYAN}${#NODES[@]}${NC}"
echo -e "成功: ${GREEN}${SUCCESS_COUNT}${NC}"
echo -e "失败: ${RED}${#FAILED_NODES[@]}${NC}"
echo -e "跳过: ${YELLOW}${#SKIPPED_NODES[@]}${NC}"
echo ""

if [ ${#FAILED_NODES[@]} -gt 0 ]; then
    echo -e "${RED}失败节点: ${FAILED_NODES[*]}${NC}"
    echo ""
fi

if [ ${#SKIPPED_NODES[@]} -gt 0 ]; then
    echo -e "${YELLOW}跳过节点: ${SKIPPED_NODES[*]}${NC}"
    echo ""
fi

# 根据结果给出建议
if [ ${SUCCESS_COUNT} -eq ${#NODES[@]} ]; then
    echo -e "${GREEN}✅ 所有节点配置更新成功！${NC}"
    echo ""
    echo -e "${YELLOW}下一步操作:${NC}"
    echo -e "  1. 运行 ${GREEN}./minio-cluster-control.sh reload${NC} 重新加载配置"
    echo -e "  2. 运行 ${GREEN}./minio-cluster-control.sh status${NC} 检查服务状态"
    echo -e "  3. 清除浏览器缓存并重新登录 MinIO Console"
    echo -e "  4. 重新生成分享链接，验证域名是否正确"
    echo ""
    exit 0
elif [ ${SUCCESS_COUNT} -gt 0 ]; then
    echo -e "${YELLOW}⚠️  部分节点更新成功${NC}"
    echo ""
    echo -e "${YELLOW}建议操作:${NC}"
    echo -e "  1. 检查失败节点的 SSH 连接和权限"
    echo -e "  2. 手动更新失败的节点"
    echo -e "  3. 重新运行此脚本"
    echo ""
    exit 1
else
    echo -e "${RED}❌ 所有节点更新失败${NC}"
    echo ""
    echo -e "${RED}可能的原因:${NC}"
    echo -e "  1. SSH 连接问题 - 检查免密登录配置"
    echo -e "  2. 权限问题 - 确保有 sudo 权限"
    echo -e "  3. 服务文件路径错误"
    echo ""
    echo -e "${YELLOW}排查步骤:${NC}"
    echo -e "  1. 测试 SSH: ${CYAN}ssh minio2 'echo test'${NC}"
    echo -e "  2. 检查文件: ${CYAN}ssh minio2 'ls -la ${SERVICE_FILE}'${NC}"
    echo -e "  3. 查看日志: ${CYAN}ssh minio2 'journalctl -u minio -n 20'${NC}"
    echo ""
    exit 1
fi

